package zt.song.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import zt.song.domain.Role;
import zt.song.domain.User;
import zt.song.mapper.RoleMapper;
import zt.song.service.UserService;
import zt.song.mapper.UserMapper;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
* @author 宋伟宁
* @description 针对表【t_user】的数据库操作Service实现
* @createDate 2023-11-23 09:50:28
*/
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
    implements UserService{

    @Resource
    private UserMapper userMapper;

    @Resource
    private RoleMapper roleMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 根据username查询
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username",username);
        var user = this.userMapper.selectOne(queryWrapper);
        // 判断是否存在
        if(null == user){
            throw new UsernameNotFoundException("对不起，账号不存在！");
        }
        // 获取角色（权限）集合
        //查询数据库
        QueryWrapper<Role> roleQueryWrapper = new QueryWrapper<Role>();
        roleQueryWrapper.eq("uid",user.getId());
        List<Role> roles = this.roleMapper.selectList(roleQueryWrapper);
         //转换为Stirng集合
        List<String> auths= roles.stream().map(Role::getAuth).collect(Collectors.toList());
        //封装到对象的角色集合中
        user.setAuthorities(AuthorityUtils.createAuthorityList(auths));
        return user;
    }
}




